package com.cms.bs.util;

import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BaseTypeUtil {

    public static Double nanDouble(Object d) {
        if (d == null) {
            return Double.NaN;
        }
        try {
            return Double.parseDouble(d.toString());
        } catch (RuntimeException e) {
            return 0d;
        }
    }

    public static Double safeDouble(Object d) {
        if (d == null) {
            return 0d;
        }
        try {
            return Double.parseDouble(d.toString());
        } catch (RuntimeException e) {
            return 0d;
        }
    }

    public static int safeInt(Object obj) {
        if (obj == null) {
            return 0;
        }
        if (obj instanceof Double) {
            return safeDouble(obj).intValue();
        }

        try {
            return Integer.parseInt(String.valueOf(obj));
        } catch (RuntimeException e) {
            return 0;
        }
    }

    public static String safeString(Object obj) {
        if (obj == null) {
            return "";
        }
        return String.valueOf(obj);
    }

    public static String safeStringUTF8(Object obj) {
        if (obj == null) {
            return "";
        }
        try {
            return new String(String.valueOf(obj).getBytes(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static Long safeLong(Object obj) {
        if (obj == null) {
            return 0L;
        }
        if (obj instanceof Double) {
            return safeDouble(obj).longValue();
        }

        try {
            return Long.parseLong(String.valueOf(obj));
        } catch (RuntimeException e) {
            return 0L;
        }
    }

    public static BigDecimal safeBigDecimal(Object object) {
        if (object == null) {
            return new BigDecimal(0);
        }
        return new BigDecimal(String.valueOf(object));
    }

    public static Object type4db2java(String db_type) {
        String javaType = "";
        switch (db_type){
            case "varchar":
                javaType = "String";
                break;
            case "int":
                javaType = "Integer";
                break;
            case "bigint":
                javaType = "Long";
                break;
            case "datetime":
            case "data":
            case "time":
                javaType = "Date";
                break;
        }
        return javaType;
    }

}
